package hotel.base.oversea.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import sun.misc.BASE64Encoder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class ApacheHttpClientExample {

    private static final String USER_AGENT = "Mozilla/5.0";

    private static final String GET_URL = "http://localhost:9090/SpringMVCExample";

    private static final String POST_URL = "http://localhost:9090/SpringMVCExample/home";

    private static final String uri="http://m.fat.ctripqa.com/restapi/soa2/13353/";
    private static final int supplierID=16551;
    private static final String key="209903b0-5f92-4759-9ea9-8723124f8c9e";

    public static void main(String[] args) throws IOException {
//        sendGET();
//        System.out.println("GET DONE");
//        sendPOST();
//        System.out.println("POST DONE");
        sentSwitchDemo();
    }



    /**
     * 測試案例
     */
    public static void sentSwitchDemo(){
        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                Map<String, Object> data = new HashMap<String, Object>();
                Map<String, Object> requestor = new HashMap<String, Object>();
                requestor.put("invoker","demo");
                requestor.put("operatorName","demo");
                requestor.put("opClientIP","127.0.0.1");
                requestor.put("userID",1);
                requestor.put("languageType","CN");
                data.put("requestor", requestor);
                data.put("supplierID", supplierID);
                //获取 timestamp
                String timestamp=String.valueOf(System.currentTimeMillis());
                //计算 signature
                String tmp=String.valueOf(supplierID)+String.valueOf(System.currentTimeMillis())+key;
                MessageDigest md5 = MessageDigest.getInstance("MD5");
                BASE64Encoder base64en = new BASE64Encoder();
                String signature=base64en.encode(md5.digest(tmp.getBytes("utf-8"))).toUpperCase();
                //组装 http 请求数据
                HttpPost httpPost = new HttpPost(uri + "getdltcountrylist");
                httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json");
                httpPost.setHeader("timestamp", timestamp);
                httpPost.setHeader("signature", signature);
                httpPost.setEntity(new StringEntity(objectMapper.writeValueAsString(data),
                        ContentType.create("text/json", "UTF-8")));
                client = HttpClients.createDefault();
                response = client.execute(httpPost);
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity);
                System.out.println(httpPost);
                System.out.println("request timestamp:"+timestamp);
                System.out.println(result);


                JSONObject jsonObject = JSONObject.fromObject(result);
                JSONObject countryInfoList = jsonObject.getJSONObject("countryInfoList");
                JSONArray jsonArray = countryInfoList.getJSONArray("countryInfo");
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void sendGET() throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(GET_URL);
        httpGet.addHeader("User-Agent", USER_AGENT);
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);

        System.out.println("GET Response Status:: "
                + httpResponse.getStatusLine().getStatusCode());

        BufferedReader reader = new BufferedReader(new InputStreamReader(
                httpResponse.getEntity().getContent()));

        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = reader.readLine()) != null) {
            response.append(inputLine);
        }
        reader.close();

        // print result
        System.out.println(response.toString());
        httpClient.close();
    }

    private static void sendPOST() throws IOException {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(POST_URL);
        httpPost.addHeader("User-Agent", USER_AGENT);

        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("userName", "Pankaj Kumar"));

        HttpEntity postParams = new UrlEncodedFormEntity(urlParameters);
        httpPost.setEntity(postParams);

        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);

        System.out.println("POST Response Status:: "
                + httpResponse.getStatusLine().getStatusCode());

        BufferedReader reader = new BufferedReader(new InputStreamReader(
                httpResponse.getEntity().getContent()));

        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = reader.readLine()) != null) {
            response.append(inputLine);
        }
        reader.close();


        // print result
        System.out.println(response.toString());
        httpClient.close();

    }


}
